package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.CommentType;
import com.tanhua.dubbo.server.vo.IdType;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.management.Query;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class QuanZiService {
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    PicUploadService picUploadService;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;


    /**
     * 业务层实现功能:获取圈子好友的动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult friendQuanZiPublish(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //获取根据用户id获取好友的动态
        PageInfo<Publish> pageInfo = quanZiApi.friendQuanZiPublish(userId, page, pageSize);
        if (CollUtil.isEmpty(pageInfo.getRecords())) {
            //没有好友动态,返回结果集
            return pageResult;
        }
        //封装好友的动态信息
        ArrayList<QuanZiVo> quanZiVos = this.fillQuanZiXinXi(pageInfo.getRecords());
        //返回结果集
        pageResult.setItems(quanZiVos);
        return pageResult;
    }

    /**
     * 根据用户id查询用户发布的动态
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findMeAllPublish(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.get();
        //根据用户id获取动态
        PageInfo<Publish> pageInfo = quanZiApi.meQuanZiPublish(userId, page, pageSize);
        if (CollUtil.isEmpty(pageInfo.getRecords())) {
            //没有动态,返回结果集
            return pageResult;
        }
        //封装自己的动态信息
        ArrayList<QuanZiVo> quanZiVos = this.fillQuanZiXinXi(pageInfo.getRecords());
        //返回结果集
        pageResult.setItems(quanZiVos);
        pageResult.setCounts(pageInfo.getTotal());
        return pageResult;
    }


    /**
     * 业务层实现功能:封装圈子好友的动态信息
     *
     * @param publishs
     * @return
     */
    private ArrayList<QuanZiVo> fillQuanZiXinXi(List<Publish> publishs) {
        ArrayList<QuanZiVo> quanZiVos = new ArrayList<>();
        for (Publish publish : publishs) {
            QuanZiVo quanZiVo = new QuanZiVo();
            //封装动态信息
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", publish.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            //封装用户信息
            fillQuanZiUserInfo(userInfo, quanZiVo);
            quanZiVos.add(quanZiVo);
        }

        return quanZiVos;
    }

    /**
     * 实现功能:封装对应动态的的用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillQuanZiUserInfo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().toString());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
        User user = UserThreadLocal.get();
        Long userId = user.getId();

        //距离
        quanZiVo.setDistance("2.2公里");//TODO
        //点赞数
        quanZiVo.setLikeCount(Convert.toInt(quanZiApi.likeAndLoveCount(userId, quanZiVo.getId(), CommentType.LIKE)));//TODO
        //是否点赞
        quanZiVo.setHasLiked(quanZiApi.judgeUserLikeAndLove(userId, quanZiVo.getId(), CommentType.LIKE) ? 1 : 0);//TODO
        //评论数
        quanZiVo.setCommentCount(Convert.toInt(quanZiApi.likeAndLoveCount(userId, quanZiVo.getId(), CommentType.COMMENT)));//TODO
        //喜欢数
        quanZiVo.setLoveCount(Convert.toInt(quanZiApi.likeAndLoveCount(userId, quanZiVo.getId(), CommentType.LOVE)));//TODO
        //是否喜欢
        quanZiVo.setHasLoved(quanZiApi.judgeUserLikeAndLove(userId, quanZiVo.getId(), CommentType.LOVE) ? 1 : 0);//TODO
    }

    /**
     * 业务层实现功能:根据用户id获取系统推荐动态
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult recommendedQuanZiPublish(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //获取根据用户id获取系统推荐的动态
        PageInfo<Publish> pageInfo = quanZiApi.recommendedQuanZiPublish(userId, page, pageSize);
        if (CollUtil.isEmpty(pageInfo.getRecords())) {
            //没有系统推荐的动态,返回结果集
            return pageResult;
        }
        //封装系统推荐的动态信息
        ArrayList<QuanZiVo> quanZiVos = this.fillQuanZiXinXi(pageInfo.getRecords());
        //返回结果集
        pageResult.setItems(quanZiVos);
        return pageResult;
    }

    /**
     * 业务层实现功能:发布动态
     *
     * @param textContent
     * @param location
     * @param latitude
     * @param longitude
     * @param files
     * @return
     */
    public String savePublishRelease(String textContent, String location, String latitude, String longitude, MultipartFile[] files) {
        //根据token校验的结果,获取用户信息
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //创建发布的动态对象
        Publish publish = new Publish();
        publish.setUserId(userId);
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        publish.setLatitude(latitude);
        publish.setSeeType(1);
        //上传所有图片,并将照片的上传路径封装到动态的对象中
        List<String> picUrls = new ArrayList<>();
        //上传图片
        for (MultipartFile file : files) {
            PicUploadResult upload = picUploadService.upload(file);
            if (upload.getName() != null) {
                picUrls.add(upload.getName());
            }
        }
        publish.setMedias(picUrls);
        return quanZiApi.savePublish(userId, publish);
    }

    /**
     * 业务层实现点赞,喜欢,动态功能,点赞评论等
     *
     * @param publishId
     * @param like
     * @return
     */
    public Long likeAndLove(String publishId, CommentType like, IdType type) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //1.对动态或评论进行点赞或者喜欢
        if (!quanZiApi.likeAndLove(userId, publishId, like, null, type)) {
            //点赞或者喜欢失败
            return null;
        }
        //2.点赞或者喜欢成功,返回点赞或者喜欢的数量
        return quanZiApi.likeAndLoveCount(userId, publishId, like);
    }


    /**
     * 业务层实现取消===>点赞,喜欢,动态功能,点赞评论等
     *
     * @param publishId
     * @param like
     * @return
     */
    public Long likeCancelAndLove(String publishId, CommentType like, IdType type) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //1.对动态或评论进行点赞或者喜欢(取消)
        if (!quanZiApi.cancelLikeAndLove(userId, publishId, like, null, type)) {
            //点赞或者喜欢失败
            return null;
        }
        //2.(取消)点赞或者喜欢成功,返回点赞或者喜欢的数量
        return quanZiApi.likeAndLoveCount(userId, publishId, like);
    }

    /**
     * 查询单条动态
     *
     * @param publishId
     * @return
     */
    public QuanZiVo getOnePublish(String publishId) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        Publish publish = quanZiApi.getOnePublish(publishId);
        QuanZiVo quanZiVo = new QuanZiVo();
        //封装动态信息
        quanZiVo.setId(publish.getId().toHexString());
        quanZiVo.setUserId(publish.getUserId());
        quanZiVo.setTextContent(publish.getText());
        quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
        quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", publish.getUserId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        //封装用户信息
        fillQuanZiUserInfo(userInfo, quanZiVo);
        return quanZiVo;
    }


    /**
     * 保存对动态的评论
     *
     * @param movementId
     * @param comment
     * @return
     */
    public Boolean saveCommentPublish(String movementId, String comment) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        Boolean aBoolean = quanZiApi.saveLikeAndLoveAndComment(userId, movementId, CommentType.COMMENT, comment, IdType.PUBLISH);
        return aBoolean;
    }

    /**
     * 获取指定动态的所有评论
     *
     * @param publishId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findAllComment(String publishId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        List<CommentVo> commentVos = new ArrayList<>();
        List<Comment> comments = quanZiApi.findAllComments(page, pageSize, publishId);
        for (Comment comment : comments) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(comment.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "HH:mm"));
            commentVo.setContent(comment.getContent());
            User user = UserThreadLocal.get();
            Long userId = user.getId();
            commentVo.setLikeCount(Convert.toInt(quanZiApi.likeAndLoveCount(userId, commentVo.getId(), CommentType.LIKE)));
            commentVo.setHasLiked(quanZiApi.judgeUserLikeAndLove(userId, commentVo.getId(), CommentType.LIKE) ? 1 : 0);
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", comment.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            commentVo.setAvatar(userInfo.getLogo());
            commentVo.setNickname(userInfo.getNickName());
            commentVos.add(commentVo);
        }
        pageResult.setItems(commentVos);
        return pageResult;

    }

    /**
     * 查询所有的访客
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        try {
            User user = UserThreadLocal.get();
            Long userId = user.getId();
            List<Visitors> visitors = visitorsApi.queryMyVisitor(userId);
            //查询所有的访客信息
            List<Object> userIds = CollUtil.getFieldValues(visitors, "visitorUserId");
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.in("user_id",userIds);
            List<UserInfo> userInfos = userInfoMapper.selectList(wrapper);
            //封装访客的信息
            List<VisitorsVo> visitorsVos = new ArrayList<>();
            for (Visitors visitor : visitors) {
                VisitorsVo visitorsVo = new VisitorsVo();
                for (UserInfo userInfo : userInfos) {
                    if(userInfo.getUserId()==visitor.getVisitorUserId()){
                        visitorsVo.setId(userInfo.getUserId());
                        visitorsVo.setAge(userInfo.getAge());
                        visitorsVo.setAvatar(userInfo.getLogo());
                        visitorsVo.setGender(userInfo.getSex().toString().toLowerCase());
                        visitorsVo.setNickname(userInfo.getNickName());
                        visitorsVo.setTags(StrUtil.split(userInfo.getTags(),',').toArray(new String[]{}));
                        break;
                    }
                }
                visitorsVos.add(visitorsVo);
            }
            return visitorsVos;
        } catch (Exception e) {
            return null;
        }
    }
}
